package com.suzhe.ymall.common.interceptor;

import com.suzhe.ymall.common.utils.YMConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
public class RestTemplateAuthInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {
        HttpHeaders headers = request.getHeaders();
        HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = servletRequest.getHeader(YMConstant.ACCESS_TOKEN);
        String source = servletRequest.getHeader(YMConstant.REQUEST_SOURCE);
        headers.add(YMConstant.ACCESS_TOKEN, token);
        headers.add(YMConstant.REQUEST_SOURCE,source);
        log.debug("RestTemplateAuthInterceptor token:{},source:{}",token,source);
        // 保证请求继续被执行
        return execution.execute(request, body);
    }

}
